package edu.fit5046.mymonashmate.activity;

import java.util.concurrent.ExecutionException;

import org.json.JSONException;
import org.json.JSONObject;

import edu.fit5046.mymonashmate.R;
import edu.fit5046.mymonashmate.utils.DetailInfo;
import edu.fit5046.mymonashmate.utils.HttpUtils;
import edu.fit5046.mymonashmate.utils.SimpleInfo;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Toast;

public class RegisterActivity extends Activity implements OnClickListener {
	public static final String TAG = "Register";
	public static final int INFO_END = DetailInfo.INFO_PREVIOUSJOB + 1;
	public static final String url1 = "/entity.pin/create";
	public static final String url2 = "/entity.mymonashmates/create";
	public static final String url3 = "/entity.idunits/create";
	public static final int unitNumber = 10;
	private static final String inv = "1Nvi5IblE";

	private EditText editTextRegInfo[];
	private EditText editTextID;
	private EditText editTextPassword1;
	private EditText editTextPassword2;

	private LinearLayout layoutUsr;
	private LinearLayout layoutInfo;

	private boolean isInfoView = false;
	private boolean[] checkResult; // unit check rel

	CheckBox box0;
	CheckBox box1;
	CheckBox box2;
	CheckBox box3;
	CheckBox box4;
	CheckBox box5;
	CheckBox box6;
	CheckBox box7;
	CheckBox box8;
	CheckBox box9;

	@Override
	protected void onCreate(Bundle savedInstanceState) {

		setContentView(R.layout.layout_register);
		initWidget();
		checkResult = new boolean[unitNumber];
		super.onCreate(savedInstanceState);
	}

	@Override
	public void onClick(View view) {
		switch (view.getId()) {
		case R.id.button_register_next:
			try {
				next();
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (ExecutionException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			break;

		case R.id.button_register_cancel:
			setResult(RESULT_OK);
			finish();
			break;
		case R.id.button_Course:
			selectCourse();
			break;
		case R.id.button_Unit:
			selectUnit();
			break;
		default:
			break;
		}

	}

	@SuppressLint("NewApi")
	private void initWidget() {

		editTextRegInfo = new EditText[INFO_END];
		editTextRegInfo[DetailInfo.INFO_NAME] = (EditText) findViewById(R.id.text_Name);
		editTextRegInfo[DetailInfo.INFO_SURNAME] = (EditText) findViewById(R.id.text_SurName);
		editTextRegInfo[DetailInfo.INFO_COURSE] = (EditText) findViewById(R.id.text_Course);
		editTextRegInfo[DetailInfo.INFO_UNIT] = (EditText) findViewById(R.id.text_Unit);
		editTextRegInfo[DetailInfo.INFO_NATIONNANITY] = (EditText) findViewById(R.id.text_NNanity);
		editTextRegInfo[DetailInfo.INFO_FIRSTLANGUAGE] = (EditText) findViewById(R.id.text_FLanguage);
		editTextRegInfo[DetailInfo.INFO_SECONDLANGUAGE] = (EditText) findViewById(R.id.text_SLanguage);
		editTextRegInfo[DetailInfo.INFO_ADDRESS] = (EditText) findViewById(R.id.text_address);
		editTextRegInfo[DetailInfo.INFO_FAVOURITEFOOD] = (EditText) findViewById(R.id.text_FFood);
		editTextRegInfo[DetailInfo.INFO_FAVOURITEMOIVE] = (EditText) findViewById(R.id.text_FMovie);
		editTextRegInfo[DetailInfo.INFO_FAVOURITEUNIT] = (EditText) findViewById(R.id.text_FUnit);
		editTextRegInfo[DetailInfo.INFO_FAVOURITEPROLAN] = (EditText) findViewById(R.id.text_FProLanguage);
		editTextRegInfo[DetailInfo.INFO_CURRENTJOB] = (EditText) findViewById(R.id.text_CJob);
		editTextRegInfo[DetailInfo.INFO_PREVIOUSJOB] = (EditText) findViewById(R.id.text_PJob);

		editTextID = (EditText) findViewById(R.id.edit_StuID);
		editTextPassword1 = (EditText) findViewById(R.id.edit_Password);
		editTextPassword2 = (EditText) findViewById(R.id.edit_RePassword);

		box0 = (CheckBox) findViewById(R.id.box0);
		box1 = (CheckBox) findViewById(R.id.box1);
		box2 = (CheckBox) findViewById(R.id.box2);
		box3 = (CheckBox) findViewById(R.id.box3);
		box4 = (CheckBox) findViewById(R.id.box4);
		box5 = (CheckBox) findViewById(R.id.box5);
		box6 = (CheckBox) findViewById(R.id.box6);
		box7 = (CheckBox) findViewById(R.id.box7);
		box8 = (CheckBox) findViewById(R.id.box8);
		box9 = (CheckBox) findViewById(R.id.box9);

		layoutUsr = (LinearLayout) findViewById(R.id.layout_register_usr);
		layoutInfo = (LinearLayout) findViewById(R.id.layout_register_info);

		Button registerButton = (Button) findViewById(R.id.button_register_next);
		Button cancelButton = (Button) findViewById(R.id.button_register_cancel);

		Button courseButton = (Button) findViewById(R.id.button_Course);
		Button unitButton = (Button) findViewById(R.id.button_Unit);
		Button okButton = (Button) findViewById(R.id.up_ok);
		Button clButton = (Button) findViewById(R.id.up_cancel);
		okButton.setVisibility(View.GONE);
		clButton.setVisibility(View.GONE);

		courseButton.setOnClickListener(this);
		unitButton.setOnClickListener(this);
		registerButton.setOnClickListener(this);
		cancelButton.setOnClickListener(this);

		editTextRegInfo[DetailInfo.INFO_COURSE].setEnabled(false);
		editTextRegInfo[DetailInfo.INFO_UNIT].setEnabled(false);
		String a = editTextRegInfo[DetailInfo.INFO_UNIT].getText().toString();
		System.out.println(a.isEmpty());
	}

	private void next() throws JSONException, InterruptedException,
			ExecutionException {

		DetailInfo info = new DetailInfo();

		if (!isInfoView) {
			if (setUser(info) != 0) {
				return;
			}
			isInfoView = true;
			layoutUsr.setVisibility(View.GONE);
			layoutInfo.setVisibility(View.VISIBLE);
		} else {

			if (getInfoFromWidget(info) != 0) {
				return;
			}
			// upload to server

			Intent intent = new Intent();
			intent.setClass(this, MapActivity.class);
			startActivity(intent);
			finish();

		}

	}

	@SuppressLint("NewApi")
	private int setUser(DetailInfo info) throws JSONException,
			InterruptedException, ExecutionException {
		Log.i("TAG", "setUser");
		String tmp;
		tmp = editTextID.getText().toString();
		if (tmp.length() < 3) {
			Toast.makeText(this, "ID too short", Toast.LENGTH_LONG).show();
			setFocus(editTextID);

			return -1;

		}
		JSONObject js = new JSONObject();
		info.ID = Integer.valueOf(tmp);
		SimpleInfo.localId = info.ID;
		js.put("stuId", info.ID);

		tmp = editTextPassword1.getText().toString();

		if (tmp.length() < 2) {
			Toast.makeText(this, "Password too short", Toast.LENGTH_LONG)
					.show();
			setFocus(editTextPassword1);
			return -1;
		}
		if (!editTextPassword2.getText().toString().equals(tmp)) {
			Toast.makeText(this, "Password not same", Toast.LENGTH_LONG).show();
			setFocus(editTextPassword1);
			return -1;
		}
		info.password = tmp;
		js.put("pin", info.password);

		String result = new MyTask().execute(url1, js.toString()).get();
		Log.i(js.toString(), result);
		if (result.contains("success")) {
			js.remove("pin");
			return 0;
		} else {
			Toast.makeText(this, "Duplicated StuID found", Toast.LENGTH_LONG)
					.show();
			return -1;
		}
	}

	@SuppressLint("NewApi")
	private int getInfoFromWidget(DetailInfo info) throws JSONException,
			InterruptedException, ExecutionException {
		String value;
		for (int i = 0; i < INFO_END; i++) {
			value = editTextRegInfo[i].getText().toString();
			if (value.isEmpty()) {
				if (!checkCanBeNull(i)) {
					Toast.makeText(this, "Input *", Toast.LENGTH_LONG).show();
					setFocus(editTextRegInfo[i]);
					return -1;
				}
			}
			info.SetInfo(i, value);
		}
		if (box0.isChecked())
			info.nationNanity += inv;
		if (box1.isChecked())
			info.firstLanguage += inv;
		if (box2.isChecked())
			info.secondLanguage += inv;
		if (box3.isChecked())
			info.address += inv;
		if (box4.isChecked())
			info.favouriteFood += inv;
		if (box5.isChecked())
			info.favouriteMovie += inv;
		if (box6.isChecked())
			info.favouriteUnit += inv;
		if (box7.isChecked())
			info.favouriteProgremLanguage += inv;
		if (box8.isChecked())
			info.currentJob += inv;
		if (box9.isChecked())
			info.previousJob += inv;
		JSONObject js = new JSONObject();
		js = info.toJson();
		js.put("stuId", SimpleInfo.localId);
		System.out.println(js.toString());
		String result = new MyTask().execute(url2, js.toString()).get();
		if (result.contains("success")) {
			// {"idUnitsPK":{"course":"BSB2342","sid":10011}} Simple

			JSONObject unitPK = new JSONObject();
			JSONObject unit = new JSONObject();
			String units[] = js.getString("unit").split(",");
			for (int i = 0; i < units.length; i++) {
				unit.put("sid", SimpleInfo.localId);
				unit.put("course", units[i]);
				unitPK.put("idUnitsPK", unit);
				
				String resultUnit = new MyTask().execute(url3, unitPK.toString()).get();
				System.out.println(resultUnit);
			}

			Toast.makeText(this, result, Toast.LENGTH_LONG).show();
			return 0;
		} else {
			Toast.makeText(this, "Server Declined", Toast.LENGTH_LONG).show();
			return -1;
		}

	}

	private void setFocus(EditText editText) {
		editText.setFocusable(true);
		editText.setFocusableInTouchMode(true);
		editText.requestFocus();
		editText.requestFocusFromTouch();

	}

	private boolean checkCanBeNull(int index) {
		if ((index == DetailInfo.INFO_NAME)
				|| (index == DetailInfo.INFO_SURNAME)
				|| (index == DetailInfo.INFO_COURSE)
				|| (index == DetailInfo.INFO_UNIT))
			return false;
		return true;
	}

	private void selectCourse() {
		final String[] items = { "Master of IT Professional",
				"Bachelor of Economics", "Honours Visual Arts",
				"Doctor of Philosophy", "Master of Business", };
		new AlertDialog.Builder(RegisterActivity.this)
				.setTitle("Select Course")
				.setItems(items, new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int item) {
						editTextRegInfo[DetailInfo.INFO_COURSE]
								.setText(items[item]);
					}
				}).show();
	}

	private void selectUnit() {
		final String[] items = { "FIT5046", "FIT5047", "CIF1234", "BSB2234",
				"FIT5167", "FIT5171", "CIF1023", "BSB2342", "CIF6699",
				"BSB1314" };
		new AlertDialog.Builder(RegisterActivity.this)
				.setTitle("Select Unit")
				.setMultiChoiceItems(items, checkResult,
						new DialogInterface.OnMultiChoiceClickListener() {
							@Override
							public void onClick(DialogInterface dialog,
									int which, boolean isChecked) {

								checkResult[which] = isChecked;

							}
						})
				.setPositiveButton("Comfirm",
						new DialogInterface.OnClickListener() {
							public void onClick(
									DialogInterface dialoginterface, int i) {
								String showString = "";
								for (int count = 0; count < unitNumber; count++) {
									if (checkResult[count]) {
										showString += (items[count] + ",");
									}
								}
								showString = showString.substring(0,
										showString.length() - 1);
								editTextRegInfo[DetailInfo.INFO_UNIT]
										.setText(showString);
								dialoginterface.dismiss();
							}
						}).show();

	}

	private class MyTask extends AsyncTask<String, Integer, String> {

		@Override
		protected String doInBackground(String... prm) {
			// TODO Auto-generated method stub

			return HttpUtils.Post(prm[0], prm[1]);
		}

		protected void onPostExecute(String result) {
			super.onPostExecute(result);
		}

	}
}
